import 'package:dio/dio.dart';

class Lanzoujx {
  // 设置 User-Agent
  static const String ua =
      "mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/114.0.0.0 safari/537.36";
  //
  String ajaxurl = "/ajaxm.php";
  Dio dio = Dio(BaseOptions(
    headers: {'user-agent': ua},
  ));

  // 获取直链
  Future<String> getZL(String ul) async {
    final String zl;
    RegExp reg = RegExp(r'\?password=(.+)');
    // 正则取密码
    Iterable<Match> matchArr = reg.allMatches(ul);
    if (matchArr.isNotEmpty) {
      print("有密码->[${matchArr.first[1]}]");
      zl = await _getzlmima(ul, matchArr.first[1].toString());
    } else {
      print("无密码-> $ul");
      List fnstr = await _getiframe(ul);
      print("数据 ---> $fnstr");
      zl = await _parseiframe(fnstr[0], fnstr[1]);
    }
    return await getzllocation(zl);
  }

  Future<String> getzllocation(String url) async {
    // print("解析成直链 ---> $url");
    // --------------------- Dio 库实现
    Dio diozl = Dio(BaseOptions(
      headers: {
        'user-agent': ua,
        "sec-ch-ua":
            '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "Linux",
        "upgrade-insecure-requests": "1",
        "accept":
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "sec-fetch-site": "cross-site",
        "sec-fetch-mode": "navigate",
        "sec-fetch-user": "?1",
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh-CN,zh;q=0.9"
      },
      method: "GET",
      followRedirects: false,
      validateStatus: (status) {
        return status! < 500;
      },
    ));
    Response res = await diozl.request(url);
    String redirectUri = res.headers['location']!.first.toString();
    // --------------------- http 库实现
    // http.Request req = http.Request("Get", Uri.parse(url))..followRedirects = false;
    // req.headers.addAll({
    //   'user-agent': ua,
    //   "sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
    //   "sec-ch-ua-mobile": "?0",
    //   "sec-ch-ua-platform": "Linux",
    //   "upgrade-insecure-requests": "1",
    //   "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    //   "sec-fetch-site": "cross-site",
    //   "sec-fetch-mode": "navigate",
    //   "sec-fetch-user": "?1",
    //   "accept-encoding": "gzip, deflate, br",
    //   "accept-language": "zh-CN,zh;q=0.9"
    // });
    // http.Client baseClient = http.Client();
    // http.StreamedResponse res = await baseClient.send(req);
    // String redirectUri = res.headers['location'].toString();
    // // print("location--->${redirectUri.toString()}");

    return redirectUri;
  }

  /// 有密码  _getzlmima(String 网址, String 密码)
  Future<String> _getzlmima(String url, String p) async {
    Response res =
        await dio.get(url, options: Options(headers: {"Referer": url}));
    // 去除空格和换行
    String resdata = res.data.toString().replaceAll(RegExp(r"[\n\t\r\f]"), "");
    // print(resdata);
    RegExp dataRe = RegExp(r"ajax\((.*?)\)");
    var matchArr = dataRe.allMatches(resdata);
    // print("data--->${matchArr.elementAt(1).group(0)}");
    if (matchArr.isNotEmpty) {
      String ajax = matchArr.elementAt(1).group(0).toString();
      var sign = RegExp(r"'sign':'(.*?)',").firstMatch(ajax)!.group(1)!;
      ajaxurl = RegExp(r"url : '(.*?)',").firstMatch(ajax)!.group(1)!;
      // var datas = RegExp(r"data : (.+),").firstMatch(ajax)!.group(1)!;
      Uri ul = Uri.parse(url);
      String okul = "${ul.scheme}://${ul.host}$ajaxurl";
      Object data = {"action": "downprocess", "sign": sign, "p": p, "kd": 1};
      // print("$url --> URL-->$okul,Data--->$data");
      Response postres = await dio.post(okul,
          data: data,
          options: Options(headers: {
            // post  Referer 这个必不可少
            "Referer": url,
            "Accept": "application/json, text/javascript, */*",
            "Content-Type": "application/x-www-form-urlencoded",
            'user-agent': ua,
          }));
      var zl = postres.data;
      if (zl['zt']! == 1) {
        String fakezl = "${zl['dom']}/file/${zl['url']}";
        // print("完成---> $zl");
        return fakezl;
      } else {
        print("失败---> ${zl['inf']}");
        return zl['inf'];
      }
    }
    return "error";
  }

  // 获取第二步链接网址
  Future<List> _getiframe(String url) async {
    dio.options.headers.addAll(
      {
        "Accept":
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
      },
    );
    Response res = await dio.get(url);
    // print("$res");
    RegExp regifr2 = RegExp(r'<iframe class="ifr2" name="\d{2,}" src="(.*?)"');
    RegExp fid = RegExp(r"	var fid = (\d+);");
    var fidVar = fid.allMatches(res.data.toString());
    Iterable<Match> matchArr = regifr2.allMatches(res.data);
    if (matchArr.isNotEmpty) {
      Uri ul = Uri.parse(url);
      String okul = "${ul.scheme}://${ul.host}${matchArr.first[1]}";
      // print("有iframe-> ${matchArr.first[1]} \n  Ok url = $okul");
      return [okul, fidVar.first[1]];
    }
    return [];
  }

  Future<String> _parseiframe(String uri, String fid) async {
    dio.options.headers
        .addAll({"Accept": "application/json, text/javascript, */*"});
    Response res = await dio.get(uri);
    // print(res);
    RegExp sign = RegExp(r"wp_sign = '(.*?)';");
    RegExp ajaxdata = RegExp(r"ajaxdata = '(.*?)';");
    var matchSign = sign.allMatches(res.data.toString());
    var matchAJAX = ajaxdata.allMatches(res.data.toString());
    if (matchSign.isNotEmpty) {
      Map<String, Object?> data = {
        'action': 'downprocess',
        'signs': matchAJAX.first[1],
        'websignkey': matchAJAX.first[1],
        'sign': matchSign.first[1],
        'websign': "",
        'kd': 1,
        'ves': 1
      };
      print("数据--->$data");

      Uri ul = Uri.parse(uri);
      // String okul = ajaxurl.replaceAll('./', "${ul.scheme}://${ul.host}/");
      String okul = "${ul.scheme}://${ul.host}$ajaxurl?file=$fid";
      print(okul);

      Response postres = await dio.post(okul,
          data: data,
          options: Options(headers: {
            "Referer": uri,
            "Accept": "application/json, text/javascript, */*",
            "Content-Type": "application/x-www-form-urlencoded",
            'user-agent': ua,
          }));

      //{ 失败
      // "zt": 0,
      // "dom": "https://develope.lanzoug.com",
      // "url": 0,
      // "inf": "已超时，请刷新"
      // }
      // { 成功
      // "zt": 1,
      // "dom": "https://develope.lanzoug
      //  url:"xxxxxxxxxxxx",
      // inf : 0
      // }
      print("------$postres");
      var zl = postres.data;
      if (zl['zt']! == 1) {
        String fakezl = "${zl['dom']}/file/${zl['url']}";
        // print("完成---> $fakezl");
        return fakezl;
      } else {
        print("失败---> ${zl['inf']}");
        return zl['inf'];
      }
    }
    return "error";
  }
}
